package control;

import entity.Category;
import entity.Image;
import entity.Product;
import entity.ProductAvailability;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import org.apache.commons.fileupload.FileItem;
import utils.ServletUtil;

@WebServlet(name = "NewProduct", urlPatterns = {"/backend/NewProduct"})
public class NewProduct extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Formulier gegevens
        boolean formSucces = false;
        Map<String, FileItem> formFields;
        
        // JPA
        EntityManagerFactory fact = Persistence.createEntityManagerFactory("vh11i_jeePU");
        EntityManager em = fact.createEntityManager();
        
        // Beans (deze moeten worden opgeslagen)
        Product product = new Product();
        Image img = new Image();
        request.setAttribute("product", product);
        
        try {
            // Haal de categorieen op voor de selectbox
            Query query = em.createNamedQuery("allCategories", Category.class);
            List<Category> categories = query.getResultList();
            request.setAttribute("categories", categories);
            
            if(request.getMethod().equals("POST")) {
                
                // Vang het multipart request op
                formFields = ServletUtil.parseMultipartRequest(request);
                
                // Vang de image op
                img.setImage(formFields.get("image").get());
                img.setMimeType(formFields.get("image").getContentType());
                
                // Zoek de gekozen categorie op
                long categoryId = ServletUtil.getLong(formFields.get("categoryId").getString(), -1);
                Category category = em.find(Category.class, categoryId);
                
                // Parse de prijs
                double price = ServletUtil.getDouble(formFields.get("price").getString(), 0);

                // Haal de beschikbaarheid Enum op
                int ordinal = ServletUtil.getInt(formFields.get("availability").getString(), 0);
                ProductAvailability availability = ProductAvailability.values()[ordinal];
                
                // Set de bean properties
                product.setName(formFields.get("name").getString());
                product.setCategory(category);
                product.setAvailability(availability);
                product.setPrice(price);
                product.setDescription(formFields.get("description").getString());
                
                if (img.getImage().length > 0) {
                    product.setImage(img);
                }

                // Valideer de bean
                //if (product.getName().length() > 0) {
                    // Sla de bean op met JPA
                    em.getTransaction().begin();
                    em.persist(product);
                    em.getTransaction().commit();
                    formSucces = true;
                //}
            }
            else {
                // Dit zorgt er voor dat de dropdown de eerste keer staat
                // ingesteld op de categorie waar de gebruiker vandaan kwam
                long categoryId = ServletUtil.getLong(request.getParameter("category_id"), -1);
                Category category = em.find(Category.class, categoryId);
                product.setCategory(category);
            }
        }
        catch(ConstraintViolationException ex) {
            request.setAttribute("formError", ex.getConstraintViolations());
        }finally {
            em.close();
            fact.close();
        }
        
        if (formSucces) {
            response.sendRedirect("NewProduct?success=true&category_id=" + product.getCategory().getId());
        } else {
            RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/newProduct.jsp");
            dispatcher.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
